<!--
  选部门
-->
<template>
  <a-modal
    :width="960"
    :body-style="{ height: '520px' }"
    wrap-class-name="common-content dept-select-content vxe-table--ignore-clear"
    :centered="true"
    :open="visible"
    :keyboard="false"
    :destroy-on-close="true"
    :mask-closable="false"
    @cancel="closeModal"
  >
    <div class="popup-title">
      <h2>
        {{ title }}
        <a-tooltip v-if="titleTips" placement="top">
          <template #title>
            <span>{{ titleTips }}</span>
          </template>
          <avic-icon svg="avic-question-fill" />
        </a-tooltip>
      </h2>
    </div>
    <div class="popup-content">
      <div class="container-left">
        <a-input-search ref="searchInput" :placeholder="searchPlaceholder" style="width: 100%; margin-bottom: 8px" @search="hanleSearch" />
        <a-tree
          ref="deptSelectTree"
          v-model:checkedKeys="treeCheckedKeys"
          v-model:selectedKeys="treeSelectedKeys"
          v-model:expandedKeys="expandedKeys"
          :check-strictly="true"
          :height="390"
          :multiple="selectModel != 'single'"
          :checkable="selectModel != 'single'"
          :load-data="loadDataAsyn"
          :tree-data="treeData"
          :loaded-keys="loadedKeys"
          :show-line="true && { showLeafIcon: false }"
          @select="selectTree"
          @check="checkTree"
          @expand="onExpand"
          @load="onLoad"
        >
          <template v-slot:title="{ dataRef }">
            <span class="user-icon">
              <avic-icon v-if="dataRef.nodeType == 'dept'" svg="avic-organization-chart" class="tree-icon dept-icon" />
              <avic-icon v-else svg="avic-building-line" class="tree-icon org-icon" />
            </span>
            <span class="dept-select-title" :title="dataRef.title">
              <span v-if="dataRef.title.indexOf(keyword) > -1">
                {{ dataRef.title.substr(0, dataRef.title.indexOf(keyword)) }}
                <span style="color: #f50">
                  {{ keyword }}
                </span>
                {{ dataRef.title.substr(dataRef.title.indexOf(keyword) + keyword.length) }}
              </span>
              <span v-else>
                {{ dataRef.title }}
              </span>
            </span>
          </template>
        </a-tree>
      </div>
      <div class="container-right">
        <div class="container-right-top">
          已选{{ name + ` (` + selectLength + `)` }}
          <delete-outlined class="total-delete-icon" title="清空" @click="handleDelTotal" />
        </div>
        <div class="checkgroup table-wrapper">
          <s-table
            :columns="selectListColumns"
            :data-source="selectList"
            :show-header="false"
            :scroll="{ y: 380 }"
            :row-height="36"
            :pagination="false"
            children-column-name="hasChild"
          >
            <template #bodyCell="{ column, text, record }">
              <template v-if="column.key === 'title'">
                <span class="more-user-info" :title="getTitle(text, record)">
                  <span class="">
                    <avic-icon v-if="record.nodeType == 'dept'" svg="avic-organization-chart" class="tree-icon dept-icon" />
                    <avic-icon v-else svg="avic-building-line" class="tree-icon org-icon" />
                    {{ text }}
                  </span>
                  <span v-if="showMoreDeptInfo" style="color: #86909c">
                    <slot v-if="record.nodeType == 'dept'" name="moreInfo" :user-side-info="record.attributes">
                      <!-- showMoreUserInfo 为true ，显示全部 moreUserInfo 中的信息 -->
                      <span
                        v-if="typeof showMoreDeptInfo === 'boolean' && moreDeptInfo.length > 0 && record.attributes[moreDeptInfo[0]]"
                        style="display: inline-block"
                      >
                        (
                        <span v-for="(infoItem, index) in moreDeptInfo" :key="infoItem">
                          {{ record.attributes[infoItem] }}
                          <span v-if="index < moreDeptInfo.length - 1">,</span>
                        </span>
                        )
                      </span>
                      <!-- showMoreUserInfo 为数组，仅显示 showMoreUserInfo 对应的属性值 -->
                      <span v-else-if="typeof showMoreDeptInfo == 'object'">
                        (
                        <span v-for="(infoItem, index) in showMoreDeptInfo" :key="infoItem">
                          {{ record.attributes[infoItem] || '' }}
                          <span v-if="index < showMoreDeptInfo.length - 1 && record.attributes[infoItem]">/</span>
                        </span>
                        )
                      </span>
                    </slot>
                  </span>
                </span>
                <span class="checkclose" title="删除" @click="handleDelItem($event, record, 'singleDele')">
                  <avic-icon svg="avic-close-fill" />
                </span>
              </template>
            </template>
          </s-table>
        </div>
      </div>
    </div>
    <template #footer>
      <a-button title="确认" type="primary" @click="confirm">确认</a-button>
      <a-button title="取消" type="primary" ghost @click="closeModal">取消</a-button>
    </template>
  </a-modal>
</template>
<script lang="ts" setup>
import { getInitDeptInfo, httpRequest, getDeptByIds } from './api';
const { proxy } = getCurrentInstance();
const props = defineProps({
  /** 是否显示 */
  show: { type: Boolean, required: true, default: false, key: 'title' },
  /** 右侧列表已选标题文案 */
  name: { type: String, default: '部门' },
  /** 标题 */
  title: { type: String, default: '部门选择' },
  /** 辅助提示信息 */
  titleTips: { type: String, default: '' },
  /** 搜索提示 */
  searchPlaceholder: { type: String, default: '请输入部门名称' },
  /** 单选 single ，多选 multi */
  selectModel: { type: String, required: false, default: 'single' },
  /** 多选最多选择数量 */
  maxSelect: { type: Number, required: false, default: 0 },
  /** 默认值 */
  defaultValue: { type: Object, required: false, default: () => null },
  /** 双向绑定改变事件 */
  modelChange: { type: Object, required: false, default: () => null },
  /** 组织范围 */
  viewScope: { type: String, required: false, default: '' },
  /** 默认加载指定组织的id */
  defaultOrgId: { type: String, required: false, default: '' },
  /** 默认加载部门id */
  defaultLoadDeptId: { type: String, required: false, default: '' },
  /** 部门等级 */
  deptLevel: { type: Number, required: false, default: undefined },
  /** 是否显示无效部门 */
  viewSystemDept: { type: Boolean, required: false, default: false },
  /** 部门请求地址 */
  deptUrl: {
    type: String,
    required: false,
    default: '/appsys/common/select/getDeptSelectList/v1'
  },
  /** 请求类型 */
  methodType: { type: String, required: false, default: 'post' },
  /** 部门搜索请求地址 */
  deptSearchUrl: {
    type: String,
    required: false,
    default: '/appsys/common/select/getDeptSelectList/v1'
  },
  /** 选部门初始展开层级 */
  deptExpandLevel: { type: Number, default: 2 },
  /** 自定义参数 */
  customParam: { type: Object, required: false, default: null },
  /** 自定义搜索参数 */
  customSearchParam: { type: Object, required: false, default: null },
  /** 展示部门的额外信息 (数组配置的所有项目都会显示) */
  moreDeptInfo: { type: Array, default: () => ['deptNamePath', 'orgName'] },
  /** 是否展示部门附加信息 */
  showMoreDeptInfo: { type: [Boolean, Array], default: null },
  /** 树节点选中是否完全受控(不级联) */
  checkStrictly: { type: Boolean, default: false },
  /** 部门选择中是否可选组织节点 */
  orgCheckable: { type: Boolean, default: false }
});
const visible = ref(false); // 窗口是否显示
// 树组件需要的加载数据格式
const treeParam = {
  url: props.deptUrl,
  parameter: {},
  method: props.methodType
};
// 树搜索组件需要的加载数据格式
const searchTreeParam = {
  url: props.deptSearchUrl,
  parameter: {},
  method: props.methodType
};
const treeData = ref([]);
const keyword = ref('');
const searchResultFlag = ref(false);
const treeCheckedKeys = ref({}); // 树选中控制
const treeSelectedKeys = ref([]);
const expandedKeys = ref([]);
const loadedKeys = ref([]);
const maxSelectNumber = ref(0); // 最多选择数量
const selectListColumns = ref([
  {
    title: '已选部门',
    dataIndex: 'title',
    key: 'title',
    rowDrag: true
  }
]);
const selectList = ref([]); // 选中的部门
let selectListMap = {}; // 选中的部门
const selectLength = ref(0);
const treeClickCount = ref(0); // 树点击次数
const deptSelectTree = ref(null);
const searchInput = ref(null);

watch(
  () => props.show,
  (newV) => {
    visible.value = newV;
    if (newV === true) {
      nextTick(() => {
        searchInput.value?.focus();
      });
      init();
    }
  },
  { immediate: true }
);
watch(
  selectList,
  (newV) => {
    selectLength.value = newV.length;
  },
  { immediate: true }
);
watch(
  () => props.defaultValue,
  (defaultValue) => {
    if (defaultValue) {
      if (defaultValue && defaultValue.ids) {
        const ids = defaultValue.ids.split(';');
        let names = [];
        if (defaultValue.names) {
          names = defaultValue.names.split(';');
        }
        if (ids.length === names.length) {
          initDataNotHttp(defaultValue);
        } else {
          loadDefaultValue(defaultValue.ids);
        }
      } else if (Object.prototype.toString.call(defaultValue) === '[object String]') {
        loadDefaultValue(defaultValue);
      }
    }
  }
);
watch(
  () => props.modelChange,
  (newV) => {
    if (newV && newV.ids) {
      const ids = newV.ids.split(';');
      let names = [];
      if (newV.names) {
        names = newV.names.split(';');
      }
      if (ids.length === names.length) {
        initDataNotHttp(newV);
      }
    } else {
      if (selectList.value.length > 0) {
        empty();
      }
    }
  },
  { immediate: true, deep: true }
);
watch(
  () => props.maxSelect,
  (newV) => {
    if (newV > 0) {
      maxSelectNumber.value = newV;
    }
  },
  { immediate: true, deep: true }
);

onBeforeMount(() => {
  setTreeParam('', '');
  autoLoadAsyn();
});

onMounted(() => {
  // 处理默认值
  if (props.defaultValue) {
    const { defaultValue } = props;
    if (defaultValue && defaultValue.ids) {
      const ids = defaultValue.ids.split(';');
      let names = [];
      if (defaultValue.names) {
        names = defaultValue.names.split(';');
      }
      if (ids.length === names.length) {
        initDataNotHttp(defaultValue);
      } else {
        loadDefaultValue(defaultValue.ids);
      }
    } else if (Object.prototype.toString.call(defaultValue) === '[object String]') {
      loadDefaultValue(defaultValue);
    }
  }
});

const $emit = defineEmits(['close', 'callBack', 'defaultBack']);
function hanleSearch(value) {
  keyword.value = value;
  autoLoadAsyn();
}
/** 获取title */
function getTitle(text, record) {
  let str = text;
  if (props.showMoreDeptInfo && record.nodeType === 'dept') {
    const values = [];
    if (typeof props.showMoreDeptInfo == 'boolean' && props.moreDeptInfo.length > 0) {
      for (let i = 0; i < props.moreDeptInfo.length; i++) {
        if (record.attributes[props.moreDeptInfo[i]]) {
          values.push(record.attributes[props.moreDeptInfo[i]]);
        }
      }
    } else if (typeof props.showMoreDeptInfo == 'object' && props.showMoreDeptInfo.length > 0) {
      for (let i = 0; i < props.showMoreDeptInfo.length; i++) {
        if (record.attributes[props.showMoreDeptInfo[i]]) {
          values.push(record.attributes[props.showMoreDeptInfo[i]]);
        }
      }
    }
    if (values.length > 0) {
      str = `${str}(${values.join('/')})`;
    }
  }
  return str;
}

/**
 * 初始化函数
 */
function init() {
  keyword.value = '';
  setTreeParam();
  // 部门选择页展开节点后，再次打开，低几率出现已展开节点不加载的问题
  // autoLoadAsyn();
  if (!props.modelChange.ids) {
    empty();
  }
}

/**
 * 加载默认数据
 */
function loadDefaultValue(ids) {
  if (ids.value) {
    let deptids = [];
    deptids = ids.value.split(';');
    initDeptInfo(deptids);
  }
}

/**
 * 加载初始化选中的部门
 */
function initDeptInfo(data) {
  empty();
  getInitDeptInfo(data).then((res: any) => {
    if (res.success && res.data) {
      res.data.map((tim) => {
        selectList.value.push({
          id: tim.id,
          nodeType: 'dept',
          title: tim.name,
          key: tim.id,
          isLeaf: true,
          children: []
        });
        if (props.selectModel === 'multi') {
          treeCheckedKeys.value.checked.push(tim.id);
        } else {
          treeSelectedKeys.value.push(tim.id);
        }
        return tim;
      });
    }
    const result = setResultData();
    setTimeout(() => {
      $emit('defaultBack', result);
    }, 100);
  });
}

/**
 * 初始化回填部门，不去请求http
 */
function initDataNotHttp(data) {
  empty();
  // const type = 'dept';
  const ids = data.ids.split(';');
  const names = data.names.split(';');
  let deptids = [];
  let deptNames = [];
  let deptNamePaths = [];
  // selectListMap = {};
  if (data.deptid && data.deptName && data.deptNamePaths) {
    if (props.orgCheckable) {
      // 开启组织选择以后
      getDeptByIds(ids).then((res: any) => {
        if (res.success && res.data) {
          res.data.map((item) => {
            deptids.push(item.id);
            return item;
          });
        }
        deptNames = data.deptName.split(';');
        deptNamePaths = data.deptNamePaths.split(';');
        const allAttributes = getExtraAttributes(data);
        dealInitData({ ids, names, deptids, deptNames, deptNamePaths, orgNames: [] }, allAttributes);
      });
    } else {
      deptids = data.deptid.split(';');
      deptNames = data.deptName.split(';');
      deptNamePaths = data.deptNamePaths.split(';');
      const allAttributes = getExtraAttributes(props.defaultValue);
      dealInitData({ ids, names, deptids, deptNames, deptNamePaths, orgNames: [] }, allAttributes);
    }
  } else {
    initDataByHttp(data);
  }
}
function initDataByHttp(data) {
  empty();
  const ids = data.ids.split(';');
  const names = data.names.split(';');
  const deptids = [];
  const deptNames = [];
  const deptNamePaths = [];
  const orgNames = [];
  getInitDeptInfo(ids).then((res) => {
    res.data.map((item) => {
      deptids.push(item.id);
      deptNames.push(item.name);
      deptNamePaths.push(item.deptNamePath);
      orgNames.push(item.orgName);
      return item;
    });
    const allAttributes = getExtraAttributes(props.defaultValue);
    dealInitData({ ids, names, deptids, deptNames, deptNamePaths, orgNames }, allAttributes);
  });
}
// 从defaultValue 中获取附加信息
function getExtraAttributes(data = {}) {
  const attributesMap = {};
  let attrList = [];
  if (typeof props.showMoreDeptInfo == 'boolean') {
    attrList = props.moreDeptInfo;
  } else {
    attrList = props.showMoreDeptInfo;
  }
  attrList.forEach((key) => {
    if (data[key]) {
      attributesMap[key] = data[key].split(';');
    }
  });
  return attributesMap;
}
// eslint-disable-next-line max-params
function dealInitData({ ids, names, deptids, deptNames, deptNamePaths, orgNames }, allAttributes) {
  let type = 'dept';
  selectList.value = [];
  selectListMap = {};
  const attrKeys = Object.keys(allAttributes);
  ids.map((tim, i) => {
    if (Array.isArray(deptids) && deptids.length > 0) {
      // 检查是否存在 deptid 等于 tim 的情况
      const hasMatchingDept = deptids.some((deptid) => deptid === tim);
      if (!hasMatchingDept) {
        type = 'org';
      }
    } else {
      // 如果 deptids 是空数组或非数组，直接设置 type 为 'org'
      type = 'org';
    }
    const item = {
      id: tim,
      nodeType: type,
      title: names[i],
      key: tim,
      isLeaf: true,
      children: [],
      attributes: {
        deptid: deptids ? deptids[i] : '',
        deptName: deptNames ? deptNames[i] : '',
        deptNamePath: deptNamePaths ? deptNamePaths[i] : '',
        orgName: orgNames ? orgNames[i] : ''
      }
    };
    // 设置部门默认的附加信息
    attrKeys.forEach((key) => {
      if (allAttributes[key][i]) {
        item.attributes[key] = allAttributes[key][i];
      }
    });
    selectList.value.push(item);
    selectListMap[tim] = item;
    return tim;
  });
  if (props.selectModel === 'multi') {
    treeCheckedKeys.value.checked = ids;
  } else {
    treeSelectedKeys.value = ids;
  }
}
/**
 *  加载部门节点需要传的数据
 */
function setTreeParam(id = '', nodeType = '') {
  treeParam.parameter = {
    viewScope: props.viewScope,
    defaultOrgId: props.defaultOrgId,
    nodeType,
    id,
    viewSystemDept: props.viewSystemDept,
    defaultLoadDeptId: props.defaultLoadDeptId,
    deptLevel: props.deptLevel
  };
  if (Object.keys(props.customParam)) {
    Object.assign(treeParam.parameter, props.customParam);
  }
}

/**
 * 搜索部门节点需要传的数据
 */
function setTreeSearchParam(e) {
  const select = [];
  selectList.value.map((tim) => {
    select.push(tim.id);
    return tim;
  });
  searchTreeParam.parameter = {
    viewScope: props.viewScope,
    defaultOrgId: props.defaultOrgId,
    selectedDept: select.join(','),
    viewSystemDept: props.viewSystemDept,
    defaultLoadDeptId: props.defaultLoadDeptId,
    deptLevel: props.deptLevel,
    searchText: e
  };
  if (Object.keys(props.customSearchParam)) {
    Object.assign(searchTreeParam.parameter, props.customSearchParam);
  }
}

/**
 * tree 自动初始化节点
 */
function autoLoadAsyn() {
  // expandedKeys.value = [];
  loadedKeys.value = [];
  searchResultFlag.value = false;
  loadDataAsyn(null);
}

/**
 * tree 请求数据
 */
function loadDataAsyn(node) {
  return new Promise((resolve) => {
    if (node && node.children && node.children.length > 0) {
      resolve(null);
      return;
    }
    if (node && !loadedKeys.value.includes(node.id)) {
      loadedKeys.value = [...loadedKeys.value, node.id];
    }
    // 非查询条件下异步加载节点，修改treeParam传递的node的id
    if (node) {
      beforeLoadData(node);
    } else {
      // 非异步加载节点加载清除id 和nodeType
      treeParam.parameter.id = '';
      treeParam.parameter.nodeType = '';
    }
    let param = {};
    if (!keyword.value.trim() || searchResultFlag.value === true) {
      treeParam.parameter.searchText = '';
      param = treeParam;
    } else {
      setTreeSearchParam(keyword.value);
      param = searchTreeParam;
    }
    httpRequest(param.url, param.parameter ? param.parameter : '', param.method).then((res: any) => {
      if (res.success && res.data && res.data.length > 0) {
        afterLoadData(res.data);
        if (!node) {
          treeData.value = res.data;
          treeData.value = [...treeData.value];
          if (keyword.value === '') {
            nextTick(() => {
              expandedKeys.value = treeData.value ? [treeData.value[0].id] : [];
            });
          } else {
            // 全部展开
            const treeExpandedKeys = [];
            getExpandedKeys(treeData.value, treeExpandedKeys);
            expandedKeys.value = [...treeExpandedKeys];
          }
        } else {
          node.dataRef.children = res.data;
          treeData.value = [...treeData.value];
          if (node.checked && !props.checkStrictly) {
            res.data?.map((tim) => {
              if (!expandedKeys.value.includes(tim.id)) {
                expandedKeys.value.push(tim.id);
              }
              if (!treeCheckedKeys.value.checked.includes(tim.id)) {
                treeCheckedKeys.value.checked.push(tim.id);
              }
              if (!selectListMap[tim.id] && tim.nodeType === 'dept') {
                const item = proxy.$lodash.cloneDeep(tim);
                selectList.value.push(item);
                selectListMap[tim.id] = item;
                selectList.value = [...selectList.value];
              }
              return tim;
            });
          }
          nextTick(() => {
            deptSelectTree.value.scrollTo({ key: res.data[res.data.length - 1].key });
          });
        }
      } else {
        if (keyword.value !== '') {
          proxy.$message.warning('未查询到匹配数据！');
          searchResultFlag.value = true;
        }
        proxy.$message.warning(`${node.title} 节点下无数据。`);
      }
      resolve(null);
    });
  });
}

function getExpandedKeys(data, expandedKeys) {
  if (data && data.length > 0) {
    data.map((item) => {
      if (item.children && item.children.length > 0) {
        expandedKeys.push(item.id);
        getExpandedKeys(item.children, expandedKeys);
      }
      return item;
    });
  }
}

/**
 * 展开/收起节点
 */
function onExpand(treeExpandedKeys) {
  expandedKeys.value = [...treeExpandedKeys];
}

/**
 * 节点加载完毕
 */
function onLoad(treeLoadedKeys) {
  loadedKeys.value = [...treeLoadedKeys];
}

/**
 * 加载节点前事件，设置加载节点的参数
 */
function beforeLoadData(data) {
  if (data) {
    setTreeParam(data.id, data.nodeType);
  }
}

/**
 * 数据加载完成，处理数据
 */
function afterLoadData(res) {
  setTreeData(res);
}

/**
 * 处理数据
 */
function setTreeData(data) {
  if (data && data.length > 0) {
    data.map((tim) => {
      tim.disabled = false;
      if (props.selectModel === 'multi') {
        tim.selectable = false;
        if (tim.isLeaf && tim.nodeType !== 'dept') {
          tim.disableCheckbox = true;
        } else {
          tim.disableCheckbox = false;
        }
        if (tim.id === 'ORG_ROOT') {
          tim.disableCheckbox = true;
        }
      } else {
        if (tim.nodeType !== 'dept') {
          tim.selectable = props.orgCheckable;
        } else {
          tim.selectable = true;
        }
      }
      if (tim.children) {
        setTreeData(tim.children);
      }
      return tim;
    });
  }
}

/**
 * 点击树节点事件 单击 / 双击（300毫秒内连续点击两次视为双击）
 */
function selectTree(_, { selected, node }) {
  // 记录点击次数
  treeClickCount.value += 1;
  // 单次点击次数超过2次不作处理,直接返回,也可以拓展成多击事件
  if (treeClickCount.value >= 2) {
    return;
  }
  // 计时器,计算300毫秒为单位,可自行修改
  window.setTimeout(() => {
    if (treeClickCount.value === 1) {
      // 把次数归零
      treeClickCount.value = 0;
      // 单击事件
      if (selected) {
        selectListMap = {};
        selectListMap[node.id] = { ...node };
        selectList.value = [{ ...node }];
      } else {
        selectListMap = {};
        selectList.value = [];
      }
      setCheckData();
    } else if (treeClickCount.value > 1) {
      // 把次数归零
      treeClickCount.value = 0;
      // 双击事件
      if (props.selectModel === 'single') {
        if (node.nodeType === 'dept') {
          selectListMap = {};
          selectListMap[node.id] = { ...node };
          selectList.value = [{ ...node }];
          setCheckData();
          confirm();
        }
      }
    }
  }, 300);
}

/**
 * 多选点击复选框事件
 */
function checkTree(checkedKeys, { checked, checkedNodes, node }) {
  if (!node.isLeaf && !loadedKeys.value.includes(node.id)) {
    expandedKeys.value = [...expandedKeys.value, node.id];
  }
  if (props.maxSelect > 0 && checkedKeys.length > props.maxSelect) {
    proxy.$message.warning(`已设置最多选择${maxSelectNumber.value}个部门！`);
    setCheckData();
  } else {
    if (checked) {
      // 选中
      setSelectList(checkedNodes);
      setMultiCheckData(checkedNodes);
    } else {
      // 取消选中
      setUnSelectList(node, '');
      setMultiUnCheckData(node);
    }
  }
}

/** 多选选中 树节点处理 */
function setMultiCheckData(checkedNodes) {
  if (checkedNodes) {
    checkedNodes.map((tim) => {
      if (!treeCheckedKeys.value.checked.includes(tim.id)) {
        treeCheckedKeys.value.checked.push(tim.id);
      }
      if (props.checkStrictly) {
        // eslint-disable-next-line array-callback-return
        return;
      }
      if (tim.children) {
        setMultiCheckData(tim.children);
      }
      // eslint-disable-next-line consistent-return
      return tim;
    });
  }
}

/** 多选取消选中 树节点处理 */
function setMultiUnCheckData(node) {
  if (node) {
    if (treeCheckedKeys.value.checked.indexOf(node.id) > -1) {
      treeCheckedKeys.value.checked.splice(treeCheckedKeys.value.checked.indexOf(node.id), 1);
    }
    if (props.checkStrictly) {
      return;
    }
    if (node.children) {
      node.children.map((tim) => {
        setMultiUnCheckData(tim);
        return tim;
      });
    }
  }
}
/**
 * 多选选中节点时，处理右侧列表数据
 */
function setSelectList(nodes) {
  if (nodes) {
    nodes.map((tim) => {
      if (!selectListMap[tim.id] && tim.nodeType === 'dept') {
        const item = proxy.$lodash.cloneDeep(tim);
        selectList.value.push(item);
        selectListMap[tim.id] = item;
        selectList.value = [...selectList.value];
      }
      if (props.checkStrictly) {
        // eslint-disable-next-line array-callback-return
        return;
      }
      if (tim.children) {
        setSelectList(tim.children);
      }
      // eslint-disable-next-line consistent-return
      return tim;
    });
  }
}

/**
 * 多选取消选中节点时，处理右侧列表数据
 */
function setUnSelectList(node, type) {
  const childrenIds = [];
  getTarget(treeData.value, node.id, childrenIds, type);
  selectList.value = selectList.value.filter((item) => !childrenIds.includes(item.id) && item.id !== node.id);
  childrenIds.map((item) => {
    delete selectListMap[item];
    return item;
  });
}

// eslint-disable-next-line max-params
function getTarget(data, id, childrenIds, type) {
  if (data && data.length > 0 && id) {
    // eslint-disable-next-line array-callback-return
    data.map((item) => {
      if (item.id === id) {
        childrenIds.push(item.id);
        if (props.checkStrictly) {
          // eslint-disable-next-line array-callback-return
          return;
        }
        if (item.children && type !== 'singleDele') {
          getChildren(item.children, childrenIds);
        }
      } else {
        if (item.children) {
          getTarget(item.children, id, childrenIds, type);
        }
      }
    });
  }
}

function getChildren(data, childrenIds) {
  if (data && data.length > 0) {
    data.map((item) => {
      childrenIds.push(item.id);
      if (item.children) {
        getChildren(item.children, childrenIds);
      }
      return item;
    });
  }
}

/**
 * 设置单选treeSelectedKeys
 */
function setCheckData() {
  const list = [];
  selectList.value.map((tim) => list.push(tim.id));
  treeSelectedKeys.value = list;
}

/**
 * 清空右侧列表
 */
function handleDelTotal() {
  empty();
}

/**
 * 删除右侧列表单条数据
 */
function handleDelItem(e, item, type) {
  e.stopPropagation();
  if (props.selectModel === 'multi') {
    setUnSelectList(item, type);
    setMultiUnCheckData(item);
  } else {
    const list = [];
    for (let i = 0; i < selectList.value.length; i++) {
      if (selectList.value[i].id !== item.id) {
        list.push(selectList.value[i]);
      }
    }
    selectList.value = list;
    delete selectListMap[item.id];
    setCheckData();
  }
}

/**
 * 清空选中人员
 */
function empty() {
  treeCheckedKeys.value.checked = [];
  treeSelectedKeys.value = [];
  selectList.value = [];
  selectListMap = {};
}

/**
 * 清除查询条件
 */
function emptyQuery() {
  setTreeSearchParam('');
  setTreeParam('', '');
}

/**
 * 点击确定
 */
function confirm() {
  const result = setResultData();
  if (result.ids) {
    $emit('callBack', result, selectList.value);
  } else {
    $emit('callBack', {}, []);
  }
  visible.value = false;
  emptyQuery();
}

/**
 * 处理返回的数据格式
 */
function setResultData() {
  let ids = '';
  let names = '';
  let deptNamePath = '';
  if (selectList.value && selectList.value.length > 0) {
    selectList.value.map((res, i) => {
      if (i > 0) {
        ids += ';';
        names += ';';
        if (res.attributes) {
          deptNamePath += ';';
        }
      }
      ids += res.id;
      names += res.title;
      if (res.attributes) {
        deptNamePath += res.attributes.deptNamePath;
      }
      return res;
    });
  }
  let result = null;
  if (deptNamePath) {
    result = { ids, names, deptNamePath };
  } else {
    result = { ids, names };
  }
  return result;
}

/**
 * 点击取消、关闭
 */
function closeModal() {
  emptyQuery();
  $emit('close');
}
</script>
<style scoped>
.more-user-info {
  display: inline-block;
  width: 290px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  vertical-align: middle;
}
</style>
